<script setup>
import { onMounted, ref, watch } from 'vue'
import { JBoltApi } from '@/service/request'

const props = defineProps({
    url: String,
    options: {
        type: Array,
        default: () => []
    },
    labelField: {
        type: String,
        default: 'text'
    },
    valueField: {
        type: String,
        default: 'value'
    },
    valueToNumber: {
        type: Boolean,
        default: false
    },
    valueToBoolean: {
        type: Boolean,
        default: false
    }
})

// 监听url变化，重新加载数据
watch([() => props.url, () => props.options], () => {
    loadOptions()
})

const loading = ref(false)
const dynamicOptions = ref([])

function processData(data = []) {
    data.forEach((item) => {
        let value = item[props.valueField]
        if (props.valueToNumber) {
            item[props.valueField] = Number(value)
        }
        if (props.valueToBoolean) {
            item[props.valueField] =
                value == 'true' ? true : value == 'false' ? false : !!value
        }
    })
    dynamicOptions.value = data
}

function loadOptions() {
    if (!props.url) {
        processData(props.options)
        return
    }
    loading.value = true

    JBoltApi.get(props.url, null, {
        ignoreMsg: true
    })
        .then(({ error, result }) => {
            if (error) {
                dynamicOptions.value = []
                return
            }
            if (result.data) {
                processData(result.data)
            }
        })
        .finally(() => {
            loading.value = false
        })
}

onMounted(() => {
    loadOptions()
})

defineExpose({
    refresh: loadOptions
})
</script>

<template>
    <n-radio-group name="group">
        <n-space>
            <n-radio
                v-for="item in dynamicOptions"
                :key="item[props.valueField]"
                :value="
                    props.valueToNumber
                        ? Number(item[props.valueField])
                        : item[props.valueField]
                "
            >
                {{ item[props.labelField] }}
            </n-radio>
        </n-space>
    </n-radio-group>
</template>

<style scoped></style>
